<template>
  <div style="top:0; padding:5px;">
    <SnailTab v-model="currentTabName" @before-change="handleStop">
      <SnailTabPanel label="九九乘法表" name="tab1">
        <MultiplicationTable  @play="handlePlay" @palyAll="handlePalyAll" @stop="handleStop"></MultiplicationTable>
      </SnailTabPanel>
      <SnailTabPanel label="二年级乘法测验" name="tab2">
        <TestArea @play="handlePlay"></TestArea>
      </SnailTabPanel>
      <SnailTabPanel label="看图写话" name="tab3">
        <SnailWriteWords @play="handlePlay"></SnailWriteWords>
      </SnailTabPanel>
    </SnailTab>
    <audio v-show="audioRef?.muted" ref="audioRef" :muted controls>
      <source :src="audioSrc" type="audio/mpeg" />
    </audio>
  </div>
</template>

<script setup lang="ts">
import { ref } from 'vue'
import MultiplicationTable from './components/MultiplicationTable.vue'

import { SnailTab, SnailTabPanel } from './components/SnailTab'
import {SnailWriteWords} from './components/WriteWords'

import TestArea from './components/TestArea.vue'

const audioSrc = ref('')
const audioRef = ref<HTMLAudioElement>()
const muted = ref(false)

// provide('play', async (file: string) => {
//   audioSrc.value = `/sound/${file}`
//   console.log('APP:', audioSrc.value)
//   audioRef.value?.load()
//   try {
//     await audioRef.value?.play()
//     muted.value = false
//   } catch (err) {
//     muted.value = true
//     // alert('请点击左上角小喇叭打开声音')
//     audioRef.value?.play()
//   }
// })

const currentTabName = ref('tab1')


const handlePlay = async(fileName: string) => {
  // 结束之前的播放
  handleStop()
  audioSrc.value = `/sound/${fileName}`
  console.log('APP:', audioSrc.value)
  audioRef.value?.load()
  try {
    await audioRef.value?.play()
    muted.value = false
  } catch (err) {
    muted.value = true
    // alert('请点击左上角小喇叭打开声音')
    audioRef.value?.play()
  }
}

const interval = ref(0)

const handlePalyAll = async (fileNames: string[]) => {
  let index = 0
  setTimeout(()=>{
     interval.value = setInterval(async()=>{
      audioSrc.value = `/sound/${fileNames[index]}`
      // console.log('APP-play:', audioSrc.value)
      audioRef.value?.load()
      index ++
      await audioRef.value?.play()
      if(index === fileNames.length) {
        clearInterval(interval.value)
      }
    },1500)
  }, 100)
}



const handleStop = () => {
  clearInterval(interval.value)
}

</script>

<style scoped>
audio {
  position: fixed;
  top: 0;
  left: 0;
  /* width: 100px; */
}

</style>
